/**
 * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.restaurant.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.modules.restaurant.entity.UserSalary;
import org.springblade.modules.restaurant.entity.UserSalaryDay;
import org.springblade.modules.restaurant.enums.TaskStatusEnums;
import org.springblade.modules.restaurant.excel.UserSalaryDayExcel;
import org.springblade.modules.restaurant.mapper.UserSalaryDayMapper;
import org.springblade.modules.restaurant.service.IUserSalaryDayService;
import org.springblade.modules.restaurant.service.IUserSalaryService;
import org.springblade.modules.restaurant.vo.UserSalaryDayVO;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDictService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户日薪表 服务实现类
 *
 * @author Blade
 * @since 2025-02-18
 */
@Slf4j
@Service
@AllArgsConstructor
public class UserSalaryDayServiceImpl extends BaseServiceImpl<UserSalaryDayMapper, UserSalaryDay> implements IUserSalaryDayService {
	private IUserSalaryService userSalaryService;
	private IUserService userService;
	private IDictService dictService;

	@Override
	public IPage<UserSalaryDayVO> selectUserSalaryDayPage(IPage<UserSalaryDayVO> page, UserSalaryDayVO userSalaryDay) {
		return page.setRecords(baseMapper.selectUserSalaryDayPage(page, userSalaryDay));
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void gen(DateTime startTime, DateTime endTime) {
		String time = DateUtil.formatDate(startTime);
		List<UserSalary> userSalaryList = userSalaryService.list(Wrappers.<UserSalary>lambdaQuery()
			.eq(UserSalary::getStatus, TaskStatusEnums.START.getStatus())
		);
		if (userSalaryList == null || userSalaryList.isEmpty()) {
			log.info("定时生成日薪,没有用户薪资配置");
			return;
		}
		List<UserSalaryDay> userSalaryDayList = userSalaryList.stream().map(userSalary -> {
			UserSalaryDay item = new UserSalaryDay();

			item.setMonthlySalary(userSalary.getMonthlySalary());
			item.setDailySalary(userSalary.getDailySalary());
			item.setRemark(userSalary.getRemark());

			User user = userService.getById(userSalary.getUserId());
			if (user != null) {
				String deptId = user.getDeptId();
				// 截取部门id , 获取,最后一个
				String deptIdStr = deptId.substring(deptId.lastIndexOf(",") + 1);

				item.setUserId(user.getId());
				item.setUserName(user.getRealName());
				item.setCreateDept(Long.valueOf(deptIdStr));
				item.setCreateUser(user.getId());
				item.setTenantId(user.getTenantId());
			}
			item.setTime(time);
			return item;
		}).toList();

		saveBatch(userSalaryDayList);
	}

	@Override
	public BigDecimal getUserDailySalaryMonthSum(String businessTime, String tenantId) {
		String startTime = DateUtil.formatDate(DateUtil.beginOfMonth(DateUtil.parse(businessTime)));
		String endTime = DateUtil.formatDate(DateUtil.endOfMonth(DateUtil.parse(businessTime)));
		List<UserSalaryDay> userSalaryDayList = list(Wrappers.<UserSalaryDay>lambdaQuery()
			.ge(UserSalaryDay::getTime, startTime)
			.le(UserSalaryDay::getTime, endTime)
			.eq(UserSalaryDay::getTenantId, tenantId)
		);
		BigDecimal sum = BigDecimal.ZERO;
		for (UserSalaryDay userSalaryDay : userSalaryDayList) {
			sum = sum.add(userSalaryDay.getDailySalary());
		}
		return sum;
	}

	@Override
	public BigDecimal userSalaryDaySum(String day, String tenantId) {
		List<UserSalaryDay> userSalaryDayList = list(Wrappers.<UserSalaryDay>lambdaQuery()
			.eq(UserSalaryDay::getTime, day)
			.eq(UserSalaryDay::getTenantId, tenantId)
		);
		BigDecimal sum = BigDecimal.ZERO;
		for (UserSalaryDay userSalaryDay : userSalaryDayList) {
			sum = sum.add(userSalaryDay.getDailySalary());
		}
		return sum;
	}

	@Override
	public List<UserSalaryDayExcel> export(List<UserSalaryDay> salaryDays) {
		try {
			if (salaryDays.isEmpty()) {
				log.error("考勤记录为空");
				return new ArrayList<>();
			}
			return salaryDays.stream().map(item -> {
				UserSalaryDayExcel userSalaryDayExcel = new UserSalaryDayExcel();
				userSalaryDayExcel.setTime(item.getTime());
				userSalaryDayExcel.setUserName(item.getUserName());
				userSalaryDayExcel.setMonthlySalary(item.getMonthlySalary());
				userSalaryDayExcel.setDailySalary(item.getDailySalary());
				userSalaryDayExcel.setRemark(item.getRemark());
				userSalaryDayExcel.setType(dictService.getValue("attendance_type", item.getType()));
				return userSalaryDayExcel;
			}).toList();
		} catch (Exception e) {
			log.error("导出考勤记录失败", e);
			return List.of();
		}
	}

	@Override
	public boolean saveUserSalaryDay(UserSalaryDay item) {
		// 获取添加用户信息
		User user = userService.getById(item.getUserId());
		// 获取部门信息
		if (user != null) {
			String deptId = user.getDeptId();
			// 截取部门id , 获取,最后一个
			String deptIdStr = deptId.substring(deptId.lastIndexOf(",") + 1);
			item.setUserId(user.getId());
			item.setUserName(user.getRealName());
			item.setCreateDept(Long.valueOf(deptIdStr));
			item.setCreateUser(user.getId());
			item.setTenantId(user.getTenantId());

			item.setStatus(1);
			item.setIsDeleted(0);
			item.setCreateTime(DateUtil.date());
			return this.baseMapper.insert(item) > 0;
		}
		return false;
	}

	@Override
	public boolean isExist(Long id, Long userId, String time) {
		UserSalaryDay dbItem = getById(id);
		UserSalaryDay userSalaryDay = getOne(Wrappers.<UserSalaryDay>lambdaQuery()
			.eq(UserSalaryDay::getUserId, userId)
			.eq(UserSalaryDay::getTime, time)
		);
		if (userSalaryDay != null && dbItem != null) {
			return !userSalaryDay.getId().equals(dbItem.getId());
		}
		return false;
	}
}
